package com.atguigu.educenter.controller;

/*
 * @ClassName WxApiController
 * @author  忘忧君
 * @Description
 * @Version 1.0
 */

//import org.springframework.stereotype.Controller;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.atguigu.commonutils.HttpClientUtils;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;

// @CrossOrigin

/**
 * 注意这里没有配置 @RestController
 * RestController将返回json格式数据
 * controller会将结果直接返回到页面中
 */

@Api(description="三方登录方法")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    @ApiOperation(value = "登录回调方法")
    @GetMapping("callback")
    public String callback(String code, String state){

        try {
            // 1. 得到code 请求accToken
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );

            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            System.out.println(accessTokenInfo);

            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)mapAccessToken.get("access_token");
            String openid = (String)mapAccessToken.get("openid");
            System.out.println(access_token);
            System.out.println(openid);

            // 2. 通过accToken和openId获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);

            String userInfo = HttpClientUtils.get(userInfoUrl);
            HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
            String nickname = (String) userInfoMap.get("nickname");
            String headimgurl = (String) userInfoMap.get("headimgurl");

            UcenterMember member = memberService.getOpenIdMember(openid);
            if (member == null){
                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);

                memberService.save(member);
            }

            // 使用jwt根据menber对象生成token字符串
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+ jwtToken;

        } catch (Exception e) {
            throw new GuliException(20001, "登录失败");
        }

    }

    // 1.生成微信扫码二维码
    @ApiOperation(value = "生成登录二维码")
    @GetMapping("login")
    public String getWxCode(){

        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String wxOpenRedirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            wxOpenRedirectUrl = URLEncoder.encode(wxOpenRedirectUrl, "utf-8");
        } catch (Exception e) { }

        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                wxOpenRedirectUrl,
                "atguigu"
        );
        return "redirect:" + url;
    }
}
